package com.sinosoft.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

/**
 * @author loujiang
 * @date 2021/1/2 9:34 上午
 * @NOTE:
 */
@Slf4j
@Component
public class TimerFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
    {
        //声明stopwatch
        StopWatch timer = new StopWatch();
        //开启
        timer.start();
        exchange.getAttributes().put("requestTimeBegin", System.currentTimeMillis());
        return chain.filter(exchange).then(
                //钩子函数结束调用
                Mono.fromRunnable(() ->
                {
                    //打印耗时时间
                    timer.stop();
                    log.info(timer.prettyPrint());
                })
        );
    }



    @Override
    public int getOrder() {
        return 0;
    }
}
